<?php
/**
 * module kind Controller
 *
 *
 * @version $Id: KindController.php 77 2010-04-25 07:28:48Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package admin
 * @subpackage Controller
 */
class Admin_KindController extends Zend_Controller_Action
{
    function indexAction()
    {
        $this->_forward('list');
    }

    private function _resetAclCache()
    {
        // 重設acl
        $cache = Zend_Registry::get('cache');
        $cache->remove('acl_cache');
        $cache->remove('resourceAccess_cache');
    }

    function delmenuAction()
    {
        $id = $this->_request->getParam('id', 0);
        // 檢查是否有子模組
        $aclResources = new Default_Model_AclResources();
        $cc = $aclResources->getChildCount($id);

        $arr = array();
        if ($cc==0) {
            $row = $aclResources->getTable()->findBy('id',$id)->getFirst();
            $resourceId = $row->resource_id;
            $resources = new Default_Model_Resources();
            $resources->assignIdentifier($resourceId);
            $resources->delete();
            $this->_resetAclCache();
            $arr['success'] = 1;
        }
        else
        $arr['success']=0;
        $this->_helper->json($arr);
    }

    function listAction()
    {
        $form = new Admin_Form_Kind();

        if ($this->_request->isPost()) {
            $request = $this->getRequest();
            if ($form->isValid($request->getParams())) {

                $resource = new Default_Model_Resources();
                $resource->getTable()->getConnection()->beginTransaction();
                try
                {
                    $id = "res_".time();
                    $resource->id = $id;
                    $resource->title = $form->getValue('title');
                    $resource->kind = 'menu';
                    $resource->sort = 0;
                    $resource->published = $form->getValue('published');

                    $resource->save();

                    $aclResources = new Default_Model_AclResources();
                    $parentId = $form->getValue('parent_id');
                    if ($parentId=='')
                    $parentId = NULL;
                    $aclResources->parent_id = $parentId;
                    $aclResources->resource_id = $id;
                    $aclResources->save();
                    $resource->getTable()->getConnection()->commit();
                    $this->_resetAclCache();
                }
                catch ( Exception $objException )
                {
                    $resource->getTable()->getConnection()->rollback();
                }

            }
        }

        $this->view->form = $form;

        $aclResourcesView = new Default_Model_AclResourcesView();
        $this->view->moduleList = $aclResourcesView->getMenuSplit();
        //列出子模組數
        $this->view->resChild = $aclResourcesView->getChildCount();
    }

}
